package edge.display.backend.MsgHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edge.display.backend.KEY_STORE;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Objects;

/**
 * 数据处理中心
 *
 * @author Amane Hayaashi
 * @date 2020/10/23
 * @since 1.0
 */

@Component
public class QHandler {

    private static final HashMap<String, String> switchMap = new HashMap<String, String>() {
        {
            put(KEY_STORE.MSG_HELLO, "Init.onHello");
            put(KEY_STORE.MSG_TASK_NEW, "Task.onNewTask");
            put(KEY_STORE.MSG_TASK_TO, "Task.afterTaskOffloading");
            put(KEY_STORE.MSG_TASK_FL, "Task.afterRecognition");
            put(KEY_STORE.MSG_NET_COMNET, "Net.onComNet");
        }
    };

    public static void handle(String jsonString) {
        try {
            JSONObject jsonObject = JSON.parseObject(jsonString);
            String key = jsonObject.get(KEY_STORE.JSON_KEY).toString();
            JSONObject valueObject = jsonObject.getJSONObject(KEY_STORE.JSON_VALUE);
            if (Objects.isNull(key) || Objects.isNull(valueObject)) {
                throw new RuntimeException();
            }
            handle(key, valueObject);
        } catch (Exception e) {
            System.out.println("[CoreHandler] String is not a valid JSON");
        }
    }

    private static void handle(String key, JSONObject valueObject) {
        try {
            // 根据key值寻找类名方法名
            String invoker = switchMap.get(key);
            String clzName = invoker.substring(0, invoker.indexOf("."));
            String methodName = invoker.substring(invoker.indexOf(".") + 1);
            // 反射调用该静态方法
            Class<?> clz = Class.forName(String.format("edge.display.backend.MsgHandler.%sHandler", clzName));
            Method method = clz.getMethod(methodName, JSONObject.class);
            method.invoke(null, valueObject);
        } catch (Exception je) {
            je.printStackTrace();
        }
    }
}
